package middleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"organoid_public/domain/fitness"
	"organoid_public/domain/fitness/service"
	"organoid_public/global"
	"organoid_public/pkg/response"
)

type DiscernAppMiddleware struct {
	svc      service.OpenAppServiceInterface
	response *response.GinRestResponse
}

func NewDiscernAppMiddleware(response *response.GinRestResponse) *DiscernAppMiddleware {

	domainSvc, err := fitness.Service()
	if err != nil {
		global.Log.Error("middleware", "login_auth", "function", "SetupRbac", "error", err.Error())
		panic(err)
	}
	return &DiscernAppMiddleware{svc: domainSvc.OpenAppSvc, response: response}
}

func (d *DiscernAppMiddleware) HandleFunc(c *gin.Context) {
	var (
		OpenAppid string
		response  = d.response.New(c)
	)
	OpenAppid = c.Request.Header.Get("open_app_id")
	if len(OpenAppid) <= 0 {
		response.Error(errors.New("miss open_app_id")).ToJSON()
		return
	}
	res, err := d.svc.DiscernRepBelongApp(OpenAppid)
	if err != nil {
		response.Error(err).ToJSON()
		return
	}
	c.Set("OpenId", res.Id)
	c.Set("OpenAppId", res.OpenAppId)
}
